/******************************************************************************
 * @File name   :      RedemptionServiceImpl.java
 *
 * @Author      :      JIZHANGS
 *
 * @Date        :      Jul 31, 2015
 *
 * @Copyright Notice: 
 * Copyright (c) 2015 Capgemini, Inc. All  Rights Reserved.
 * This software is published under the terms of the Capgemini Software
 * License version 1.0, a copy of which has been included with this
 * distribution in the LICENSE.txt file.
 * 
 * 
 * ----------------------------------------------------------------------------
 * Date                   Who         Version        Comments
 * Jul 31, 2015 1:10:04 PM        JIZHANGS     1.0            Initial Version
 *****************************************************************************/
package com.cap.bts.crmdp.dealer.mars.service.impl;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.cap.bts.commonfunc.common.constant.SmsTemplateNoConstants;
import com.cap.bts.commonfunc.common.constant.SmsTemplateVariable;
import com.cap.bts.commonfunc.common.dto.SmsContentDetailDto;
import com.cap.bts.crmdp.dealer.activation.dao.IPackageRedemptionLinesItemDao;
import com.cap.bts.crmdp.dealer.coupon.dao.ICouponRedeemDao;
import com.cap.bts.crmdp.dealer.coupon.dao.IEligibilityDao;
import com.cap.bts.crmdp.dealer.coupon.dao.ITicketLineDefineDao;
import com.cap.bts.crmdp.dealer.coupon.domain.Eligibility;
import com.cap.bts.crmdp.dealer.coupon.domain.Ticket;
import com.cap.bts.crmdp.dealer.coupon.domain.TicketLine;
import com.cap.bts.crmdp.dealer.coupon.service.ITicKetDefineService;
import com.cap.bts.crmdp.dealer.mars.constants.MARSConstants;
import com.cap.bts.crmdp.dealer.mars.dao.IMarsRedemptionDao;
import com.cap.bts.crmdp.dealer.mars.dao.IMarsRedemptionLinesItemDao;
import com.cap.bts.crmdp.dealer.mars.domain.PackageRedemptionLinesItem;
import com.cap.bts.crmdp.dealer.mars.dto.ItemTypeInfoDto;
import com.cap.bts.crmdp.dealer.mars.dto.MarsEligibilityDto;
import com.cap.bts.crmdp.dealer.mars.dto.MessageNumDto;
import com.cap.bts.crmdp.dealer.mars.dto.PackageMarsDto;
import com.cap.bts.crmdp.dealer.mars.dto.PackageMarsListDto;
import com.cap.bts.crmdp.dealer.mars.service.IMarsMemberPackageService;
import com.cap.bts.crmdp.dealer.mars.service.IMarsRedemptionService;
import com.cap.bts.crmdp.dealer.meal.dao.IMealLineManageDao;
import com.cap.bts.crmdp.dealer.meal.domain.MeallineModel;
import com.cap.bts.crmdp.dealer.member.dao.IMaintainCarPlateDao;
import com.cap.bts.crmdp.dealer.member.dao.IMaintainMemberDao;
import com.cap.bts.crmdp.dealer.member.domain.CarPlateInfo;
import com.cap.bts.crmdp.dealer.member.domain.MemberInfo;
import com.cap.bts.crmdp.dealer.purchase.dao.IMemberPackageDao;
import com.cap.bts.crmdp.dealer.purchase.domain.MemberPackageInfo;
import com.cap.bts.crmdp.dealer.redemption.dao.IPackageRedemptionDao;
import com.cap.bts.crmdp.dealer.redemption.domain.MemberPackageRedemption;
import com.cap.bts.crmdp.dealer.redemption.dto.MemberPackageInfoResultsDto;
import com.cap.bts.crmdp.dealer.redemption.dto.MemberPackageRedemptionDto;
import com.cap.bts.crmdp.dealer.redemption.dto.MemberQueryDto;
import com.cap.bts.crmdp.dealer.redemption.dto.RedemptionSubmitDto;
import com.cap.bts.crmdp.webservice.dto.CouponDto;
import com.cap.bts.crmdp.webservice.dto.CouponItemDto;
import com.cap.bts.crmdp.webservice.dto.MarsResultDto;
import com.cap.bts.crmdp.webservice.dto.WSCrmCancelOrderResultDto;
import com.cap.bts.crmdp.webservice.dto.WSCrmOrderDto;
import com.cap.bts.crmdp.webservice.dto.WSCrmRedemptionResultDto;
import com.cap.bts.crmdp.webservice.dto.WSCrmSettlementDto;
import com.cap.bts.crmdp.webservice.dto.WSCrmSettlementResultDto;
import com.cap.bts.crmdp.webservice.mars.client.CRM2MARS;
import com.cap.bts.framework.common.constant.CommonConstants;
import com.cap.bts.framework.common.exception.AppException;
import com.cap.bts.framework.common.util.Utils;
import com.cap.bts.framework.sms.service.ISmContentService;

/**
 *
 */
@Transactional(rollbackFor = AppException.class)
@Service
public class MarsRedemptionServiceImpl implements IMarsRedemptionService {
    private static final Logger LOGGER = Logger.getLogger(MarsRedemptionServiceImpl.class);
    
    @Autowired
    private IMemberPackageDao memberPackageDao;

    @Autowired
    private IPackageRedemptionDao packageRedemptionDao;

    @Autowired
    IMaintainCarPlateDao maintainCarPlateDao;

    @Autowired
    private ISmContentService smContentService;

    @Autowired
    private IMaintainMemberDao memberDao;
    
    @Autowired
    private IMealLineManageDao iMealLineManageDao;

    @Autowired
    private ITicketLineDefineDao iTicketLineDefineDao;

    @Autowired
    private IPackageRedemptionLinesItemDao packageRedemptionLinesItemDao;
    
    @Autowired
    private IMarsMemberPackageService memberPackageService;
    
    @Autowired
    private IMarsRedemptionLinesItemDao redemptionLinesItemDao;
    
    @Autowired
    private IMarsRedemptionDao  redemptionDao;
    
    @Autowired
    private IEligibilityDao eligibilityDao;

    @Autowired
    private ITicKetDefineService ticKetDefineService;
    
    @Autowired
    ICouponRedeemDao couponRedeemDaoImpl;
    
    /**
     * {@inheritDoc} overridden:
     * 
     * @Date : 2015年9月17日
     * @see com.cap.bts.crmdp.dealer.redemption.service.IRedemptionService#getPackageListByMemberMars(com.cap.bts.crmdp.dealer.redemption.dto.MemberQueryDto)
     **/
    @Override
    public List<MemberPackageInfoResultsDto> getPackageListByMemberMars(MemberQueryDto dto)
        throws AppException {
        List<MemberPackageInfoResultsDto> results = new ArrayList<MemberPackageInfoResultsDto>();
        List<CarPlateInfo> carlist = maintainCarPlateDao.getCarPlateInfoListByCarPlateOrMemberId(
            dto.getCarPlate(), dto.getId());
        if (carlist != null && !carlist.isEmpty()) {
            dto.setCarId(carlist.get(0).getId());
        }
        List<Object[]> list = memberPackageDao.getPackageListByMember(dto);
        if (list != null && !list.isEmpty()) {
            for (int i = 0; i < list.size(); i++) {
                MemberPackageInfoResultsDto resultsDto = new MemberPackageInfoResultsDto();
                Object[] obj = (Object[]) list.get(i);
                resultsDto.setId(Long.parseLong(obj[0].toString()));
                resultsDto.setName((String) obj[1]);
                resultsDto.setPackageNumber((String) obj[2]);
                resultsDto.setStatus((Byte) obj[3]);
                resultsDto.setPurchaseDate(Utils.formatDate(CommonConstants.DATE_FORMAT_YYMMDD,
                    (Date) obj[4]));
                resultsDto.setActiveDate(Utils.formatDate(CommonConstants.DATE_FORMAT_YYMMDD,
                    (Date) obj[5]));
                resultsDto.setExpireDate(Utils.formatDate(CommonConstants.DATE_FORMAT_YYMMDD,
                    (Date) obj[6]));
                List<Object[]> unUselist = packageRedemptionDao.getPackageListDetailByPackageId(
                    resultsDto.getId(), 0);
                if (unUselist != null && !unUselist.isEmpty()) {
                    BigInteger count = new BigInteger("0");
                    for (int j = 0; j < unUselist.size(); j++) {
                        count = count.add((BigInteger) (unUselist.get(j))[4]);
                    }
                    resultsDto.setCountOfPackageLines(count);
                    resultsDto.setMemberPackageRedemptionList(unUselist);

                    List<MemberPackageRedemptionDto> mprDtos = new ArrayList<MemberPackageRedemptionDto>();
                    for (Object[] o : unUselist) {
                        MemberPackageRedemptionDto mprDto = new MemberPackageRedemptionDto();
                        mprDto.setPackageId(Long.parseLong(o[0].toString()));
                        mprDto.setLineId(Long.parseLong(o[1].toString()));
                        mprDto.setTicketName(Utils.getString(o[2]));
                        mprDto.setDescription(Utils.getString(o[3]));
                        mprDto.setCountOfPackageLines(resultsDto.getCountOfPackageLines());
                        mprDto.setUseTimes(Utils.getString(o[4]));
                        mprDto.setHasVerificationCode(Utils.getString(o[5]));
                        mprDto.setRedeemDate(Utils.formatDate(CommonConstants.DATE_FORMAT_YYMMDD,
                            (Date) obj[6]));
                        mprDto.setRedemptionId(Long.valueOf(o[7].toString()));
                        // 折扣额，折扣方式
                        mprDto.setDeductionAmount(Integer.valueOf(o[8].toString()));
                        mprDto.setDeductionMethod((String) o[9]);
                        // 取得使用明细详细
                        MeallineModel meallineModel = iMealLineManageDao.findById(Long
                            .parseLong(o[1].toString()));
                        if (meallineModel != null) {
                            List<TicketLine> ticketLineList = iTicketLineDefineDao
                                .getTicketLineInfoList(meallineModel.getTicketDefId().toString());
                            List<PackageRedemptionLinesItem> items = packageRedemptionLinesItemDao
                                .getPackageRedemptionLinesItemListByPackageIdAndTicketId(
                                    mprDto.getPackageId(), meallineModel.getTicketDefId());
                            List<CouponItemDto> itemList = new ArrayList<CouponItemDto>();
                            if (ticketLineList != null) {
                                for (PackageRedemptionLinesItem item : items) {
                                    CouponItemDto itemDto = new CouponItemDto();
                                    itemDto.setItemId(item.getId());
                                    List<Eligibility> eligibilitys=eligibilityDao.getEligibilityByTicketLineId(item.getTicketLine().getId());
                                   if( eligibilitys!=null&&!eligibilitys.isEmpty()){
                                     itemDto.setHasEligibilityDefine(1);
                                   }else{
                                     itemDto.setHasEligibilityDefine(0);
                                   }
                                    //根据TicketId来判断是否含有适用范围定义
                                    itemDto.setQuantity(item.getQuantity());
                                    itemDto.setPrice(item.getPrice());
                                    itemDto.setItemName(item.getItemName());
                                    itemList.add(itemDto);
                                }
                                mprDto.setRedemtionItemList(itemList);
                            }
                        }
                        mprDtos.add(mprDto);
                    }
                    resultsDto.setMemberPackageRedemptionListMars(mprDtos);
                    resultsDto.setHasUnused(true);
                } else {
                    resultsDto.setHasUnused(false);
                }
                List<Object[]> usedlist = packageRedemptionDao.getPackageListDetailByPackageId(
                    resultsDto.getId(), 1);
                if (usedlist != null && !usedlist.isEmpty()) {
                    resultsDto.setMemberUsedPackageRedemptionList(usedlist);
                    resultsDto.setHasUsed(true);
                } else {
                    resultsDto.setHasUsed(false);
                }
                results.add(resultsDto);
            }
        }
        return results;
    }
    
    /**
     * {@inheritDoc} overridden:
     * 
     * @Date : Aug 3, 2015
     * @see com.cap.bts.crmdp.dealer.redemption.service.IRedemptionService#checkActivicationCode(com.cap.bts.crmdp.dealer.redemption.dto.RedemptionSubmitDto)
     **/
    @Override
    public void usePackageItem(RedemptionSubmitDto dto)
        throws AppException {
        if ("Y".equals(dto.getHasVerificationCode())) {
            if (this.usePackageItemWithActiveCode(dto) == null) {
                LOGGER.error("activecode incorrect");
                throw new AppException("usePackageItem", "激活码错误,请重新输入!");
            }
        } else {
            this.usePackageItemWithoutActiveCode(dto);
        }
    }
    
    /**
     * 套餐使用 @annson
     * 
     * {@inheritDoc} 
     * overridden:
     * @Date        :      Nov 10, 2015
     * @see com.cap.bts.crmdp.dealer.mars.service.IMarsRedemptionService#usePackageItemList(com.cap.bts.crmdp.dealer.mars.dto.PackageMarsListDto)
    **/
    @Override
    public void usePackageItemList(PackageMarsListDto packageMarsListDto) throws AppException {
        
        CRM2MARS marsService = new CRM2MARS();
        WSCrmRedemptionResultDto marsDto=new WSCrmRedemptionResultDto();
        List<CouponDto> couponList=new ArrayList<CouponDto>();
        
        List<PackageMarsDto> packageList = packageMarsListDto.getPackageListDto();
        List<MemberPackageRedemptionDto> redeemList = new ArrayList<MemberPackageRedemptionDto>();
        List<MemberPackageRedemptionDto> tempRedeemList = null;

        if (packageList != null && !packageList.isEmpty()) {
            for (PackageMarsDto packageDto : packageList) {
                tempRedeemList = packageDto.getRedeemList();
                // 过滤提交数据去除未输入激活码数据
                if (tempRedeemList != null && !tempRedeemList.isEmpty()) {
                    for (MemberPackageRedemptionDto redeem : tempRedeemList) {
                        // 需要抵扣码和不需要抵扣码两种
                        if ( redeem.getIsRedeemItem()) {
                            redeemList.add(redeem);
                        }
                    }
                }
            }
            if ( !redeemList.isEmpty()) {
                for (MemberPackageRedemptionDto redeem : redeemList) {
                    // Mars改造后对dto从新赋值
                    RedemptionSubmitDto dto = new RedemptionSubmitDto();
                    dto.setSoNumber(packageMarsListDto.getSoNumber());
                    dto.setHasVerificationCode(redeem.getHasVerificationCode());
                    // redeem表中Id
                    dto.setDetailId(redeem.getRedemptionId());
                    // Package表中Id
                    dto.setId(redeem.getPackageId());
                    // 套餐定义行Id
                    dto.setLineId(redeem.getLineId());
                    //激活码
                    dto.setActivicationCode(redeem.getActivicationCode());
                    // 套餐剩余使用条目数
                    dto.setCountOfPackageLines(Integer.valueOf(redeem.getCountOfPackageLines().toString()));
                    try{
                        this.usePackageItem(dto);
                        redeem.setRedemptionId(dto.getDetailId());
                    }catch(AppException e){
                        LOGGER.error("usePackageItem"+e.getMessage());
                        throw new AppException("usePackageItemList", e);
                    }
                }
            } else {
                LOGGER.error("usePackageItemList input data null");
                throw new AppException("usePackageItemList", "请选使用择项目!");
            }
        } else {
            LOGGER.error("usePackageItemList input data null");
            throw new AppException("usePackageItemList", "请选择使用项目!");
        }
        
        if ( !redeemList.isEmpty()) {
            for (MemberPackageRedemptionDto redeem : redeemList) {
                CouponDto coupon=new CouponDto();
                MemberPackageRedemption mpr=packageRedemptionDao.findById(redeem.getRedemptionId());
                if(mpr!=null){
                    Ticket ticket=mpr.getPackageRedemptionLine().getTicket();
                    //折扣券
                    if("COUPON".equals(ticket.getTicketType())){
                        coupon.setCouponType(1);
                        //折扣类型 discountType
                        if("AMOUNT".equals(ticket.getDeductionMethod())){
                            coupon.setDiscountType(0);
                        }else{
                            coupon.setDiscountType(1);
                        }
                    //提货券
                    }else{
                        //折扣类型 discountType
                        if("AMOUNT".equals(ticket.getDeductionMethod())){
                            //预提提货券
                            coupon.setCouponType(2);
                            //数量
                            coupon.setDiscountType(0);
                        }else{
                            //普通提货券
                            coupon.setCouponType(0);
                            //数据库中为百分比(传给mars时转为null)
                            coupon.setDiscountType(null);
                        }
                    }
                 
                    coupon.setCouponNo(redeem.getRedemptionId().toString());
                    List<CouponItemDto> tempRedeemItemList=redeem.getRedemtionItemList();
                    List<CouponItemDto> redeemItemList=new ArrayList<CouponItemDto>();
                    for(CouponItemDto itemDto:tempRedeemItemList){
                        
                        //折扣券
                        if("COUPON".equals(ticket.getTicketType())){
                            itemDto.setDiscount(ticket.getDeductionAmount());
                            itemDto.setActualDiscount(null);
                            itemDto.setPrice(null);
                        //提货券
                        }else{
                            if("AMOUNT".equals(ticket.getDeductionMethod())){
                                //预提提货券
                                itemDto.setDiscount(ticket.getDeductionAmount());
                                itemDto.setActualDiscount(itemDto.getPrice());
                                itemDto.setPrice(null);
                            }
                        }
                        if(itemDto.getHasEligibilityDefine()==1){
                            if(itemDto.getItemNo()==null||"".equals(itemDto.getItemNo())){
                                throw new AppException("usePackageItem", "请选择商品！");
                            }
                            redeemItemList.add(itemDto);
                        }
                    }
                    coupon.setItemList(redeemItemList);
                    couponList.add(coupon);
                }
            }
        }
        
        /*//激活表中无使用中状态的明细时，更改卡号为已用完
        List<MemberPackageRedemptionDto> mprDtos=redeemList;
        if(mprDtos!=null&&!mprDtos.isEmpty()){
            List<MemberPackageRedemption> unUseMprs=null;
            for(MemberPackageRedemptionDto mprDto:mprDtos){
                unUseMprs=redemptionDao.getUnUseMemberPackageRedemptionByPackageId(mprDto.getPackageId());
                if(unUseMprs==null||unUseMprs.isEmpty()){
                    MemberPackageInfo usedMpi=memberPackageDao.findById(mprDto.getPackageId());
                    usedMpi.setStatus((byte) 3);
                }
            }
        }*/
       
      if(!couponList.isEmpty()){
          marsDto.setCouponList(couponList);
          marsDto.setSoNumber(packageMarsListDto.getSoNumber());
          marsDto.setServerCenter(packageMarsListDto.getDealerId().toString());
          
          MarsResultDto marsResultDto = marsService.redeemPackageItems(marsDto);
         
          if(!MARSConstants.RESULT_STATUS_CODE_SUCCESS.equals(marsResultDto.getStatusCode())){
              LOGGER.error("mars error:"+marsResultDto.getResultMessage());
              throw new AppException("usePackageItem", marsResultDto.getResultMessage());
          }
      }else{
    	  //激活表中无使用中状态的明细时，更改卡号为已用完
    	  List<MemberPackageRedemptionDto> mprDtos=redeemList;
          if(mprDtos!=null&&!mprDtos.isEmpty()){
              List<Object[]> unUseMprs=null;
              for(MemberPackageRedemptionDto mprDto:mprDtos){
                  unUseMprs=redemptionDao.getUnUseMemberPackageRedemptionListByPackageId(mprDto.getPackageId());
                  if(unUseMprs==null||unUseMprs.isEmpty()){
                      MemberPackageInfo usedMpi=memberPackageDao.findById(mprDto.getPackageId());
                      usedMpi.setStatus((byte) 3);
                  }
              }
          }
      }
      
    }
    
    /**
     * {@inheritDoc} overridden:
     * 
     * @Date : Aug 3, 2015
     * @see com.cap.bts.crmdp.dealer.redemption.service.IRedemptionService#checkActivicationCode(com.cap.bts.crmdp.dealer.redemption.dto.RedemptionSubmitDto)
     **/
    @Override
    public MemberPackageRedemption usePackageItemWithActiveCode(RedemptionSubmitDto dto)
        throws AppException {
        MemberPackageRedemption mpr = packageRedemptionDao.checkActivicationCode(dto);
        if (mpr != null) {
            mpr.setStatus(1);
            mpr.setRedeemDate(new Date());
            mpr.setSoNumberRedeem(dto.getSoNumber());
            mpr.setMarsLockStatus(1);
            packageRedemptionDao.updateMemberPackageRedemption(mpr);
            //@annson 结算时发送短信
//            sendSMSForRedeem(mpr);
        }
        
        if (dto.getCountOfPackageLines() == 1) {
            MemberPackageInfo mpi = new MemberPackageInfo();
            mpi.setId(dto.getId());
            memberPackageService.updateMemberPackageInfoById(mpi);
        }
        return mpr;
    }
    
    /**
     * {@inheritDoc} overridden:
     * 
     * @Date : 2015年9月9日
     * @see com.cap.bts.crmdp.dealer.redemption.service.IRedemptionService#useActivicationCode(com.cap.bts.crmdp.dealer.redemption.dto.RedemptionSubmitDto)
     **/
    @Override
    public MemberPackageRedemption usePackageItemWithoutActiveCode(RedemptionSubmitDto dto)
        throws AppException {
        MemberPackageRedemption mpr = packageRedemptionDao.useActivicationCode(dto);
        if (mpr != null) {
            mpr.setStatus(1);
            mpr.setRedeemDate(new Date());
            mpr.setSoNumberRedeem(dto.getSoNumber());
            mpr.setMarsLockStatus(1);
            packageRedemptionDao.updateMemberPackageRedemption(mpr);
            //@annson 使用时不发送短信，到结算时再发送
//            sendSMSForRedeem(mpr);
        }
        
        if (dto.getCountOfPackageLines() == 1) {
            MemberPackageInfo mpi = new MemberPackageInfo();
            mpi.setId(dto.getId());
            memberPackageService.updateMemberPackageInfoById(mpi);
        }
        return mpr;
    }

    @Override
    public boolean sendRedemptionCode(Long redemptionId, Long memberPackageId) throws AppException {
        // send SMS Message
        MemberPackageInfo memberPackageInfo = memberPackageDao.findById(memberPackageId);
        MemberPackageRedemption memberPackageRedemption = packageRedemptionDao
            .findById(redemptionId);
        if (memberPackageInfo != null && memberPackageRedemption != null) {
            // Send SMS
            Map<String, String> paraMap = new HashMap<String, String>();
            paraMap.put(SmsTemplateVariable.VARIABLE_PACKAGE_NAME, memberPackageRedemption
                .getShortName());
            paraMap.put(SmsTemplateVariable.VARIABLE_PACKAGE_NUM,
                memberPackageInfo.getPackageNumber());
            paraMap.put(SmsTemplateVariable.VARIABLE_REDEEM_CODE,
                memberPackageRedemption.getActivicationCode());
            SmsContentDetailDto smsDto = new SmsContentDetailDto();
            smsDto.setParaMap(paraMap);
            MemberInfo memberInfo = memberDao.findById(memberPackageInfo.getActiveMemberId());
            if (memberInfo != null && Utils.notEmpty(memberInfo.getMobilePhone())) {
                smsDto.setDestMobile(Long.valueOf(memberInfo.getMobilePhone()));
                smsDto.setTemplateNo(SmsTemplateNoConstants.PACKAGE_REDEEM_TEMPLATE_NO);
                smContentService.createSmsContent(smsDto);
            }
            return true;
        }

        return false;
    }

    private void sendSMSForRedeem(MemberPackageRedemption mpr) {
        // send SMS Message
        MemberPackageInfo memberPackageInfo = memberPackageDao.findById(mpr.getPackageId());
        if (memberPackageInfo != null && mpr.getPackageRedemptionLine() != null) {
            // Send SMS
            Map<String, String> paraMap = new HashMap<String, String>();
            paraMap.put(SmsTemplateVariable.VARIABLE_REDEEM_LINE_NAME, mpr
                .getPackageRedemptionLine().getShortName());
            SmsContentDetailDto smsDto = new SmsContentDetailDto();
            smsDto.setParaMap(paraMap);
            MemberInfo memberInfo = memberDao.findById(memberPackageInfo.getActiveMemberId());
            if (memberInfo != null && Utils.notEmpty(memberInfo.getMobilePhone())) {
                smsDto.setDestMobile(Long.valueOf(memberInfo.getMobilePhone()));
                smsDto.setTemplateNo(SmsTemplateNoConstants.PACKAGE_LINE_REDEEM_TEMPLATE_NO);
                try {
                    smContentService.createSmsContent(smsDto);
                } catch (AppException e) {
                    LOGGER.error("sendSMSForRedeem", e);
                }
            }
        }
    }
    
    /**
     * {@inheritDoc} 
     * overridden:
     * @Date        :      2015年11月10日
     * @see com.cap.bts.crmdp.dealer.coupon.service.ITicKetDefineService#getWeCareItemInfoSqlByItemId(java.lang.Long)
    **/
    @Override
    public List<ItemTypeInfoDto>  getItemTypeInfoListByItemId(ItemTypeInfoDto dto) throws AppException {
        List<ItemTypeInfoDto> itemTypeInfoDtos=new ArrayList<ItemTypeInfoDto>();
        CRM2MARS marsService = new CRM2MARS();
        //mars
        MarsEligibilityDto marsEligibilityDto=getMarsEligibilityDtoByItemId(dto);
        marsEligibilityDto.setServerCenter(dto.getServerCenter());
        MarsResultDto resultDto=marsService.itemEligibility(marsEligibilityDto);
        
        if(resultDto.getSuccessFlag()){
            List<ItemTypeInfoDto> marsItemsDtos= resultDto.getItemList();
            for(ItemTypeInfoDto marsItemsDto :marsItemsDtos){
                marsItemsDto.setItemFamily(marsEligibilityDto.getItemFamily());
            }
            itemTypeInfoDtos.addAll(marsItemsDtos);
        }else{
            LOGGER.error("mars取得数据出错"+resultDto.getResultMessage());
        }
        //wecare 不需要
        
        return  itemTypeInfoDtos;
    }
    
    /**
     * 
     * {@inheritDoc} 
     * overridden:
     * @Date        :      Nov 13, 2015
     * @see com.cap.bts.crmdp.dealer.mars.service.IMarsRedemptionService#getMarsEligibilityDtoByItemId(com.cap.bts.crmdp.dealer.mars.dto.ItemTypeInfoDto)
    *
     */
    @Override
    public MarsEligibilityDto getMarsEligibilityDtoByItemId(ItemTypeInfoDto dto) throws AppException {
        MarsEligibilityDto rtnDto=null;
        PackageRedemptionLinesItem packageRedemptionLinesItem=redemptionLinesItemDao.findById(dto.getItemId());
        if(packageRedemptionLinesItem!=null){
           rtnDto=redemptionDao.getMarsEligibilityByItemIdWithGroup(packageRedemptionLinesItem.getTicketLine().getId(),dto);
        }
        return rtnDto;
    }

    /**
     * {@inheritDoc} 
     * overridden:
     * @Date        :      Nov 16, 2015
     * @see com.cap.bts.crmdp.dealer.mars.service.IMarsRedemptionService#settementRedemption(com.cap.bts.crmdp.webservice.dto.WSCrmSettlementDto)
    **/
    @Override
    public WSCrmSettlementResultDto settementRedemption(WSCrmSettlementDto dto) {
        WSCrmSettlementResultDto resultDto=new WSCrmSettlementResultDto();
        try{
        	//@annson 2016-03-02 add
        	for(String strId : dto.getCouponList()){
        		if(org.apache.commons.lang3.StringUtils.isNotBlank(strId)){
        			Long id = Long.valueOf(strId);
        			
        			MemberPackageRedemption memberPackageRedemption = redemptionDao.findById(id);
                    memberPackageRedemption.setMarsLockStatus(0);
                    memberPackageRedemption.setSoNumberSettle(dto.getSoNumber());
                    
                    //@annson 结算时发送短信
                    sendSMSForRedeem(memberPackageRedemption);
        		}
        	}
        	
        	//判断是否需要将套餐状态更改为已用完
        	for(String strId : dto.getCouponList()){
        		if(org.apache.commons.lang3.StringUtils.isNotBlank(strId)){
        			Long id = Long.valueOf(strId);
        			//调用判断修改套餐已用完的方法
        			List<Object[]> countList = redemptionDao.getUnUseMemberPackageRedemptionCount(id);
        			Long count = null;
        			if(countList != null && !countList.isEmpty()){
        				count = Long.parseLong(String.valueOf(countList.get(0)));
        			}
        			if(count != null && count.equals(0)){
        				//套餐已用完，修改package的状态status 为 3
        				memberPackageDao.updatePackageStatusById(id);
        			}
        		}
        		break;
        	}
        	
        	/* @annson 2016-03-02 del
            List<MemberPackageRedemption> list=redemptionDao.getMemberPackageRedemptionBySoNumber(dto.getSoNumber());
            if(list!=null&&!list.isEmpty()){
                for(MemberPackageRedemption mpr:list){
                    MemberPackageRedemption memberPackageRedemption=redemptionDao.findById(mpr.getId());
                    memberPackageRedemption.setMarsLockStatus(0);
                    memberPackageRedemption.setSoNumberSettle(dto.getSoNumber());
                    
                    //@annson 结算时发送短信
                    sendSMSForRedeem(mpr);
                 }
                }
                */
            resultDto.setStatusCode("1");
        }catch(Exception e){
            LOGGER.error("", e);
            resultDto.setStatusCode("0");
            resultDto.setResultMessage(e.getMessage());
        }
        return resultDto;
    }

    /**
     * {@inheritDoc} 
     * overridden:
     * @Date        :      Nov 16, 2015
     * @see com.cap.bts.crmdp.dealer.mars.service.IMarsRedemptionService#cancelRedemption(com.cap.bts.crmdp.webservice.dto.WSCrmOrderDto)
    **/
    
    @Override
    public WSCrmCancelOrderResultDto cancelRedemption(WSCrmOrderDto dto) {
        WSCrmCancelOrderResultDto resultDto=new WSCrmCancelOrderResultDto();
        try{
            List<String> couponNos=dto.getCouponList();
            if(couponNos!=null&&!couponNos.isEmpty()){
                for(String couponNo:couponNos){
                    MemberPackageRedemption memberPackageRedemption=redemptionDao.findById(Long.valueOf(couponNo));
                    if(memberPackageRedemption!=null){
                        memberPackageRedemption.setStatus(0);
                        memberPackageRedemption.setMarsLockStatus(0);
                        memberPackageRedemption.setSoNumberRedeem(null);
                        memberPackageRedemption.setRedeemDate(null);
                        memberPackageRedemption.setSoNumberCancel(dto.getSoNumber());
                        memberPackageDao.findById(memberPackageRedemption.getPackageId()).setStatus((byte) 2); 
                    }
                }
            }
            resultDto.setStatusCode("1");
        }catch(Exception e){
            LOGGER.error(e.getMessage(), e);
            resultDto.setStatusCode("0");
            resultDto.setResultMessage(e.getMessage());
        }
        return resultDto;
    }
    
   

    /**
     * {@inheritDoc} 
     * overridden:
     * @Date        :      Nov 18, 2015
     * @see com.cap.bts.crmdp.dealer.mars.service.IMarsRedemptionService#redemption(com.cap.bts.crmdp.webservice.dto.WSCrmOrderDto)
    **/
    @Override
    public WSCrmCancelOrderResultDto cancelOrder(WSCrmOrderDto dto) {
    	WSCrmCancelOrderResultDto cancelOrderResultDto = null;
    	if(dto.getCardNumberList().isEmpty() && dto.getCouponList().isEmpty() && dto.getCouponList2().isEmpty()){
    		cancelOrderResultDto = new WSCrmCancelOrderResultDto();
    		cancelOrderResultDto.setStatusCode("0");
    		cancelOrderResultDto.setResultMessage("无数据");
    		
    		return cancelOrderResultDto;
    	}
    	
    	if(!dto.getCardNumberList().isEmpty()){
    		cancelOrderResultDto = memberPackageService.cancelOrder(dto);
    	}
    	
//    	if(cancelOrderResultDto == null || StringUtils.equals("1", cancelOrderResultDto.getStatusCode())){
    	if(!dto.getCouponList().isEmpty()){	
    		cancelOrderResultDto = cancelRedemption(dto); 
    	}
    	
    	//todo coupon 
    	if(!dto.getCouponList2().isEmpty()){
	    	try {
	    		couponRedeemDaoImpl.cancelOrder(dto.getCouponList2(), dto.getSoNumber());
				cancelOrderResultDto = new WSCrmCancelOrderResultDto();
				cancelOrderResultDto.setStatusCode("1");
				
			} catch (Exception e) {
				LOGGER.error("", e);
				cancelOrderResultDto = new WSCrmCancelOrderResultDto();
				cancelOrderResultDto.setStatusCode("0");
				cancelOrderResultDto.setResultMessage(e.getMessage());
			}
		}
    	
    	
    	return cancelOrderResultDto;
    	
    	
       /* if(dto.getCouponList()!=null&&!dto.getCouponList().isEmpty()){
            return   cancelRedemption(dto); 
        }
       return   memberPackageService.cancelOrder(dto); */
    }

    /**
     * {@inheritDoc} 
     * overridden:
     * @Date        :      Nov 18, 2015
     * @see com.cap.bts.crmdp.dealer.mars.service.IMarsRedemptionService#settement(com.cap.bts.crmdp.webservice.dto.WSCrmSettlementDto)
    **/
    @Override
    public WSCrmSettlementResultDto settementOrder(WSCrmSettlementDto dto) {
    	WSCrmSettlementResultDto settlementResultDto = null;
    	if(dto.getCardNumberList().isEmpty() && dto.getCouponList().isEmpty()&& dto.getCouponList2().isEmpty()){
    		settlementResultDto = new WSCrmSettlementResultDto();
    		settlementResultDto.setStatusCode("0");
    		settlementResultDto.setResultMessage("无数据");
    		
    		return settlementResultDto;
    	}
    	
    	
    	if(!dto.getCardNumberList().isEmpty()){
    		settlementResultDto = memberPackageService.settlement(dto);
    	}
    	
//    	if(settlementResultDto == null || StringUtils.equals("1", settlementResultDto.getStatusCode())){
    	if(!dto.getCouponList().isEmpty()){
    		settlementResultDto = settementRedemption(dto); 
//    		return settementRedemption(dto); 
    	}
    	
    	//todo coupon 
    	if(!dto.getCouponList2().isEmpty()){
	    	try {
	    		couponRedeemDaoImpl.settlement(dto.getCouponList2(), dto.getSoNumber());
				settlementResultDto = new WSCrmSettlementResultDto();
				settlementResultDto.setStatusCode("1");
			} catch (AppException e) {
				LOGGER.error("", e);
				settlementResultDto = new WSCrmSettlementResultDto();
				settlementResultDto.setStatusCode("0");
				settlementResultDto.setResultMessage(e.getMessage());
			}
	    }
	    	
	    	
    	return settlementResultDto;
    	
       /* if(dto.getCouponList()!=null&&!dto.getCouponList().isEmpty()){
            return   settementRedemption(dto); 
        }
       return   memberPackageService.settlement(dto); */
    }

	@Override
	public MessageNumDto getNumberAboutMessage(Long dealerId, String date) throws AppException {
		List<Object[]> list = redemptionDao.getNumberAboutMessage(dealerId, date);
		if(list != null && !list.isEmpty()){
			Object[] nums = list.get(0);
			
			
			MessageNumDto messageNumDto = new MessageNumDto();
			messageNumDto.setInitNumber(nums[0] == null ? "0" : nums[0] + "");
			messageNumDto.setRechargeNumber(nums[1] == null ? "0" : new BigDecimal(nums[1].toString()).intValue()+"");
			messageNumDto.setSendNumber(nums[2] == null ? "0" : nums[2].toString());
			messageNumDto.setBalanceNumber(nums[3] == null ? "0" : nums[3].toString());
			messageNumDto.setTodayNumber(nums[4] == null ? "0" : nums[4].toString());
			return messageNumDto;
		}
		return null;
	}
	
	
	
    @Override
    public List<ItemTypeInfoDto>  getItemListForCoupon(ItemTypeInfoDto dto) throws AppException {
        List<ItemTypeInfoDto> itemTypeInfoDtos=new ArrayList<ItemTypeInfoDto>();
        CRM2MARS marsService = new CRM2MARS();
        //mars
        MarsEligibilityDto marsEligibilityDto = redemptionDao.getMarsEligibilityByItemIdWithGroup(dto.getTicketLineId(), null);
        marsEligibilityDto.setServerCenter(dto.getServerCenter());
        MarsResultDto resultDto=marsService.itemEligibility(marsEligibilityDto);
        
        if(resultDto.getSuccessFlag()){
            List<ItemTypeInfoDto> marsItemsDtos= resultDto.getItemList();
            for(ItemTypeInfoDto marsItemsDto :marsItemsDtos){
                marsItemsDto.setItemFamily(marsEligibilityDto.getItemFamily());
            }
            itemTypeInfoDtos.addAll(marsItemsDtos);
        }else{
            LOGGER.error("mars取得数据出错"+resultDto.getResultMessage());
        }
        //wecare 不需要
       
        
        return  itemTypeInfoDtos;
    }
    
    
}
